<template>
  <el-dialog
    :title="dialog.title"
    :visible.sync="dialog.show"
    :before-close="beforeClose"
    :close-on-click-modal="false"

  >
    <!--v-alterELDialogMarginTop="{marginTop:'20px'}"-->
    <div class="form-container address-book">
      <el-form :model="addressBook" ref="form" label-width="80px" :rules="rules">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addressBook.name"></el-input>
        </el-form-item>

        <el-row class="show-add-parent">
          <el-col :span="20">
            <el-form-item label="分组" prop="userGroupId">
              <el-select v-model="addressBook.userGroupId">
                <el-option v-for="(item,index) in groupList" :key="index" :value="item.value"
                           :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" style="text-align: right">
            <el-button @click="showAdd = !showAdd" v-text="showAdd ? '取消添加' : '添加分组'"></el-button>
          </el-col>

          <transition name="group-add">
            <el-row v-if="showAdd" class="add-group">
              <div class="mask"></div>
              <div class="arrow"></div>
              <el-row>
                <el-col :span="20">
                  <el-form-item label="分组名称">
                    <el-input v-model="temp"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="4" class="add-btn-wrap">
                  <el-button @click="addGroup" :disabled="temp.trim() === ''">添加</el-button>
                </el-col>
              </el-row>
            </el-row>
          </transition>

        </el-row>

        <div class="phone-wrap">
          <el-form-item label="手机号码" prop="temp2">
            <el-input v-model="addressBook.temp2">
              <el-button slot="append" icon="el-icon-plus"
                         @click="addOrMinus(true,true)"></el-button>
            </el-input>
          </el-form-item>
          <transition-group name="component-fade" tag="div">
            <el-form-item label="手机号码" v-for="(item,index) in phoneList" :key="item.key">
              <el-input v-model="item.value">
                <el-button slot="append" icon="el-icon-minus"
                           @click="addOrMinus(false,true,index)"></el-button>
              </el-input>
            </el-form-item>
          </transition-group>

        </div>

        <div class="more-info-wrap">
          <transition-group name="component-fade" tag="div">
            <el-form-item label="更多信息" v-for="(item,index) in moreInfoList" :key="item.key">
              <el-input v-model="item.value" class="input-with-select">
                <el-select v-model="item.typeId" slot="prepend" placeholder="请选择">
                  <el-option :label="val.label" :value="val.value" v-for="val in infoTypeList"
                             :key="val.value"></el-option>
                </el-select>
                <el-button slot="append" :icon="index === 0 ? 'el-icon-plus' : 'el-icon-minus'"
                           @click="addOrMinus(index===0,false,index)"></el-button>
              </el-input>
            </el-form-item>
          </transition-group>
        </div>

        <el-form-item label="电子邮件" prop="email">
          <el-input v-model="addressBook.email"></el-input>
        </el-form-item>


        <el-form-item label="备注" prop="beiZhu">
          <el-input type="textarea" :rows="3" v-model="addressBook.beiZhu"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="uploadHost+'/fileUpload/upload?fileType=UserHeadPic'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-progress="onProgress"
            :on-error="onError"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p class="tip" style="line-height: 15px;" v-text="tipText"></p>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <el-button type="default" @click="close">取 消</el-button>
      <el-button type="danger" @click="resetForm">重 置</el-button>
      <el-button
        type="success"
        @click="submitForm"
        :loading="dialog.changeLoading">保 存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import simpleValidate from '@/utils/simpleValidate'
  import addressBookAPI from '@/api/addrbook/addbok'
  import {mapGetters} from 'vuex'

  export default {
    name: 'AddressBookSave',
    data() {
      const validPhone = (rule,value,callback)=>{
        if(value && !simpleValidate.validPhone(value)){
          callback(new Error('手机号码格式不正确'))
        }else{
          callback()
        }
      }
      const validEmail = (rule,value,callback)=>{
        if(value && !simpleValidate.validEmail(value)){
          callback(new Error('邮箱格式不正确'))
        }else{
          callback()
        }
      }
      return {
        showDialog: false,
        title: '新建联系人',
        changeLoading: false,
        addressBook: {
          beiZhu: '',
          email: '',
          mobileList: [],
          moreInfoList: [],
          name: '',
          photo: '',
          userGroupId: '',
          temp2: ''
        },
        rules: {
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          userGroupId: [
            { required: true, message: '请选择分组', trigger: 'change' }
          ],
          temp2: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            {validator:validPhone,trigger: 'blur'}
          ],
          email:[
            {validator:validEmail,trigger: 'blur'}
          ]
        },
        groupList: [],
        showAdd: false,
        temp: '',
        imageUrl: '',
        phoneList: [],
        moreInfoList: [],
        infoTypeList: [],
        dialog:{
          title:'新建联系人',
          show:false,
          changeLoading:false
        },
        tipText:''
      }
    },
    created() {
      this.init()
      this.getGroupList()
      this.getInfoTypeList()
    },
    computed:{
      ...mapGetters([
        'uploadHost'
      ])
    },
    methods: {
      getInfoTypeList(){
        addressBookAPI.infoType().then(res=>{
          this.infoTypeList = res.result
          this.moreInfoList.push({
            key: Symbol(),
            value: '',
            typeId: this.infoTypeList[0].value
          })
        })
      },
      init() {
        // this.phoneList.push()
      },
      beforeClose(done) {
        this.resetForm()
        done(true)
      },
      open(id) {
        if(id){
          addressBookAPI.getById(id).then(res=>{
            console.log(res)
            this.addressBook = res
            // mobileList
            // moreInfoList
            this.imageUrl = this.addressBook.photo
            this.addressBook.temp2 = this.addressBook.mobileList[0]
            for(let i = 1;i<this.addressBook.mobileList.length;i++){
              this.phoneList.push({
                key: Symbol(),
                value: this.addressBook.mobileList[i]
              })
            }


            if(this.addressBook.moreInfoList.length !== 0){
              this.moreInfoList[0].value = this.addressBook.moreInfoList[0].value
              this.moreInfoList[0].typeId = this.addressBook.moreInfoList[0].typeId
            }
            for(let i=1;i<this.addressBook.moreInfoList.length;i++){
              this.moreInfoList.push({
                key: Symbol(),
                value: this.addressBook.moreInfoList[i].value,
                typeId: this.addressBook.moreInfoList[i].typeId
              })
            }
            console.log('this.moreInfoList',this.moreInfoList)
          })
        }
        this.dialog.show = true

      },
      getGroupList() {
        addressBookAPI.groupListBySelect().then(res => {
          this.groupList = res.result
        })
      },
      addGroup() {
        addressBookAPI.addGroup(this.temp).then(res => {
          this.$message.success('添加分组成功')
          this.showAdd = false
          this.temp = ''
          this.getGroupList()
        })
      },
      handleAvatarSuccess(res, file) {
        this.imageUrl = res.result.webFilePath
        this.addressBook.photo = res.result.webFilePath
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.info('上传头像图片大小不能超过 2MB!')
        }
        return isLt2M
      },
      addOrMinus(isAdd, isPhone,index) {
        if(isAdd){
          if (isPhone) {
            this.phoneList.push({
              key: Symbol(),
              value: ''
            })
          } else {
            this.moreInfoList.push({
              key: Symbol(),
              value: '',
              typeId: this.infoTypeList[0].value
            })
          }
        }else{
          if (isPhone) {
            this.phoneList.splice(parseInt(index), 1)
          } else {
            this.moreInfoList.splice(parseInt(index), 1)
          }
        }
      },
      close() {
        this.resetForm()
        this.dialog.show = false
      },
      resetForm() {
        this.$refs['form'].resetFields()
        this.phoneList.splice(0,this.phoneList.length)
        this.moreInfoList.splice(1,this.moreInfoList.length)
        this.moreInfoList[0].typeId = this.infoTypeList[0].value
        this.moreInfoList[0].value = ''
        this.imageUrl = ''
      },
      submitForm() {
        this.addressBook.mobileList.push(this.addressBook.temp2)
        for (let val of this.phoneList) {
          this.addressBook.mobileList.push(val.value)
        }
        this.addressBook.moreInfoList = this.moreInfoList
        this.$refs['form'].validate(valid => {
          if (valid && !this.changeLoading) {
            this.saveOrUpdate()
          }
        })
      },
      saveOrUpdate(){
        // 1:个人 2：公司
        this.dialog.changeLoading = true
        const promise = this.addressBook.id ? addressBookAPI.edit(this.addressBook)
          : addressBookAPI.save(this.addressBook,1)
        promise.then(res=>{
          this.dialog.changeLoading = false
          this.close()
          this.$message.success('添加成功')
          this.$emit('update')
        })
      },
      onProgress(e){
        this.tipText = '上传中……'+e.percent+'%'
      },
      onError(){
        this.$message.error('文件上传失败，请重试')
      }
    }
  }
</script>

<style lang="scss">
  .address-book {
    .avatar-uploader .el-upload {
       border: 1px dashed #d9d9d9;
       border-radius: 6px;
       cursor: pointer;
       position: relative;
       overflow: hidden;
     }

    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }

    .avatar-uploader-icon {
      $num: 138px;
      font-size: 28px;
      color: #8c939d;
      width: $num;
      height: $num;
      line-height: $num;
      text-align: center;
    }

    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }


    .input-with-select {
      .el-input-group__prepend {
        background-color: #fff;
      }

      .el-select .el-input {
        width: 100px;
      }
    }

  }

  .test {
    .el-input {
      width: 0;
    }
  }
</style>

<style scoped lang="scss">

  .show-add-parent {
    position: relative;
  }

  .add-group {
    background-color: white;
    position: absolute;
    left:0;
    right: 0;
    top:50px;
    padding-top: 25px;
    margin-bottom: 25px;
    box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
    border-radius: 5px;
    overflow: initial;
    z-index: 9;

    .mask {
      width: 50px;
      height: 20px;
      background-color: white;
      position: absolute;
      top: 0;
      right: 0;
      z-index: 2;
    }

    .arrow {
      position: absolute;
      right: 20px;
      top: -5px;
      width: 20px;
      height: 20px;
      background-color: white;
      transform: rotate(45deg);
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
      z-index: 1;
      /*border: 1px solid red;*/
    }
  }

  .add-btn-wrap {
    position: relative;
    text-align: right;
    padding-right: 10px;
    box-sizing: border-box;
  }

  .component-fade-enter-active, .component-fade-leave-active {
    transition: all .2s ease;
  }

  .component-fade-enter, .component-fade-leave-to {
    opacity: 0;
    transform: translateX(-20px);
  }

  .group-add-enter-active,.group-add-leave-active {
    transition: all .3s ease-in-out;
  }

  .group-add-enter,.group-add-leave-to {
    opacity: 0;
  }

  .tip {
    font-size: 13px;
  }

</style>
